package com.epam.edu.task01.tourismP;

import com.epam.edu.task01.tourism.voucher.VouchersList;
import org.apache.log4j.Logger;

import java.io.*;

public class FileWorks {
	private static Logger logger = Logger.getLogger(FileWorks.class);

	@SuppressWarnings("finally")
	public static VouchersList ReadFromFileVoucherList() throws IOException {
		DataInputStream in = null;
		VouchersList vouchersList = new VouchersList();
		try {
			FileInputStream fstream = new FileInputStream(
					"src/main/resources/input.txt");
			in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String inputString;
			int i = 1;
			while ((inputString = br.readLine()) != null) {
				int index = inputString.indexOf("|"), length = inputString
						.length();
				if (index >= 0) {
					String voucherType = inputString.substring(0, index);
					String voucherData = inputString.substring(index + 1,
							length);
					vouchersList.addVoucher(voucherType, voucherData);
				} else {
					logger.info("Number " + Integer.toString(i)
							+ " in a row incorrectly entered data");
				}
				i++;
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			in.close();
			return vouchersList;
		}

	}
}
